class_name StateChartManager
extends Node

## 简单的StateChart状态和行为管理器
## 负责接受状态更新、初始化对应行为、通知对应行为

#region 属性
@export var state_actions:Node
var state_dict:Dictionary = {}
var state_action_dict:Dictionary = {}
#endregion
#region 字段
var chart:StateChart:
	get():
		if not chart:
			chart = _find_chart(self)
		return chart
var state_action_node:Node:
	get():
		if not state_action_node:
			state_action_node = find_child("StateActions")
			if not state_action_node:
				state_action_node = Node.new()
				state_action_node.name = "StateActions"
				add_child(state_action_node)
		return state_action_node
#endregion
#region 信号
#endregion

#region 基类方法
#endregion
#region 抽象方法，子类必须实现
func get_entity() -> Entity:
	return null
#endregion
#region 公共方法
func init():
	var queue = []
	queue.push_back(chart)
	while queue.size() > 0:
		var item = queue.pop_front()
		if item is State:
			state_dict[item.name] = item
		for child in item.get_children():
			queue.push_back(child)
	for action in state_actions.get_children():
		if action is not StateChartStateActionBase:
			continue
		action = action as StateChartStateActionBase
		action.init(self,get_state_by_name(action.state_name))
func get_state_by_name(state_name:StringName) -> State:
	if state_dict.has(state_name):
		return state_dict[state_name]
	return null
func get_state_action_by_name(state_name:StringName) -> StateChartStateActionBase:
	return state_action_node.find_child(state_name)
#endregion
#region 私有方法
func _find_chart(node:Node) -> StateChart:
	for child in node.get_children():
		if child is StateChart:
			return child
		else:
			return _find_chart(child)
	return null
#endregion
#region 生命周期函数
func _init() -> void:
	init.call_deferred()
#endregion
